<?php
namespace Src\Controller;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Src\utils\AuthEnum;
use Src\utils\ResponseUtils;
use Src\utils\UserUtils;
use Src\utils\JWTUtils;
use Src\config\Db;

class AuthController
{
        private $db;

        // constructor receives container instance
        public function __construct(Db $db)
        {
                $this->db = $db;
        }

        // 用户注册
        // post /auth/register
        public function register(ServerRequestInterface $request, ResponseInterface $response)
        {
                $data = $request->getParsedBody();
                // 验证数据
                if (!$this->validateRegistrationData($data)) {
                        return ResponseUtils::errorwithEnum($response, AuthEnum::VALIDATE_FAILED);
                }

                // 检查用户名和邮箱是否已存在
                $user = $this->db->fetch("SELECT * FROM user WHERE username = ? OR email = ?", array($data["username"], $data["email"]));
                if ($user) {
                        return ResponseUtils::errorwithEnum($response, AuthEnum::USER_ALREADY_EXISTS);
                }

                // 创建新用户
                $hashedPassword = password_hash($data['password'], PASSWORD_DEFAULT);

                $this->db->fetch(
                        "INSERT INTO user (username, email, password) VALUES (?, ?, ?)",
                        array($data['username'], $data['email'], $hashedPassword)
                );

                $userId = $this->db->lastInsertId();
                $resData = [
                        'user_id' => $userId,
                        'username' => $data['username'],
                        'email' => $data['email'],
                ];
                return ResponseUtils::okwithEnum(response: $response, data: $resData, msgEnum: AuthEnum::REGISTER_SUCCESS);
        }

        // 用户登录
        // post /auth/login
        public function login(ServerRequestInterface $request, ResponseInterface $response)
        {
                $data = $request->getParsedBody();
                // 查找用户
                $user = $this->db->fetch(
                        "SELECT * FROM user WHERE username = ?",
                        [$data['username']]
                );

                if (!$user || !password_verify(password: $data['password'], hash: $user['password'])) {
                        return ResponseUtils::errorwithEnum($response, AuthEnum::INVALID_CREDENTIALS);
                }

                // 生成JWT令牌
                $token = JWTUtils::generateToken($user);
                // 拷贝$user信息,排除password
                $user = array_merge($user, ['userId' => $user['id']]);
                $user = array_diff_key($user, array_flip(['password', 'id']));
                $resData = [
                        "code" => 200,
                        "success" => true,
                        "message" => "login success",
                        "data" => [
                                "data" => $user,
                                "token" => $token
                        ]
                        //         'id' => $user['id'],
                        //         'username' => $user['username'],
                        //         'email' => $user['email'],
                        //         'role' => $user['role']
                        // ]

                ];
                // 将token 存放到headers中
                $response = $response->withHeader('Authorization', 'Bearer ' . $token);
                // 将数据存储到 SESSION 中
                $_SESSION['user'] = $resData;
                return ResponseUtils::withJson($response, $resData, 200);
        }

        public function logout(ServerRequestInterface $request, ResponseInterface $response)
        {
                // 清除SESSION
                unset($_SESSION['user']);
                session_destroy();
                return ResponseUtils::ok($response, data: "");
        }
        // 修改密码
        public function changePassword(ServerRequestInterface $request, ResponseInterface $response)
        {
                $user = UserUtils::getCurrentUser($request);
                $data = $request->getParsedBody();

                // 验证当前密码
                $dbUser = $this->db->fetch(
                        "SELECT * FROM user WHERE id = ?",
                        [$user->id]
                );

                if (!password_verify($data['current_password'], $dbUser['password'])) {
                        return ResponseUtils::errorWithEnum($response, AuthEnum::INVALID_CREDENTIALS_PASSWORD);
                }

                // 更新密码
                $newPassword = password_hash($data['new_password'], PASSWORD_DEFAULT);

                $this->db->fetch(
                        "UPDATE user SET password = ? WHERE id = ?",
                        [$newPassword, $user->id]
                );
                return ResponseUtils::okwithEnum(response: $response, data: '', msgEnum: AuthEnum::PASSWORD_CHANGED_SUCCESS);
        }

        // 重置密码
        public function resetPassword(ServerRequestInterface $request, ResponseInterface $response)
        {
                $current_user = UserUtils::getCurrentUser($request);
                $user_id = $request->getAttribute('user_id');
                if ($current_user->role !== 'admin') {
                        return ResponseUtils::errorWithEnum($response, AuthEnum::PERMISSION_DENIED);
                }
                $reset_passwd = $_ENV['RESET_PASSWD'];
                $reset_passwd = password_hash($reset_passwd, PASSWORD_DEFAULT);
                $this->db->execute("UPDATE user SET password = ? WHERE id = ?", [$reset_passwd, $user_id]);
                return ResponseUtils::ok($response, '');
        }

        // 验证注册数据
        private function validateRegistrationData($data)
        {
                return isset($data['username'], $data['email'], $data['password']) &&
                        !empty($data['username']) &&
                        !empty($data['email']) &&
                        filter_var($data['email'], FILTER_VALIDATE_EMAIL) &&
                        strlen($data['password']) >= 6;
        }


}
